package switchviz.recording;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

import switchviz.core.data.IData;
import switchviz.core.data.IDataEventListener;
import switchviz.core.signal.Signal;


public class RecordSignal extends Signal implements IDataEventListener
{
	private static Logger logger = Logger.getLogger(RecordSignal.class);
	
	private File _path = null;
	private BufferedWriter _writer = null;
	
	private Object _prevDataValue = null;

	/* c'tors ****************************************************************/
	public RecordSignal(File path, String aliasName) throws RecordingException
	{
		this(path, aliasName, 0);
	}

	public RecordSignal(File path, String aliasName, int port) throws RecordingException
	{
		super(aliasName, port);
		
		_path = path;
		
		open();
	}

	/* events ****************************************************************/
	public void valueChanged(IData data)
	{
		if (data.getValue() == null)
			return;
		
		if (_prevDataValue == null || !_prevDataValue.equals(data.getValue()))
		{
			write();
			
			_prevDataValue = data.getValue();
		}
	}
	
	protected void dataChanged()
	{
		getData().addEventListener(this);
		
		super.dataChanged();
	}

	/* methods ***************************************************************/		
	public void write()
	{
		try
		{
			_writer.write(getData().getTimeStamp().getValue() + "\t" + getData().getValue() + "\n");
		}
		catch(Exception e)
		{
			logger.error("Error writing record for '" + getAliasName() + "'.", e);
		}
	}
	
	public void close() throws RecordingException
	{
		try
		{
			_writer.close();
		} catch(IOException e)
		{
			throw new RecordingException("Error closing buffered writer for '" + getAliasName() + "'.", e);
		}
	}
		
	private void open() throws RecordingException
	{
		try
		{
			_writer = new BufferedWriter(new FileWriter(getRecordFile()));
		} catch(IOException e)
		{
			throw new RecordingException("Error creating buffer writer for '" + getAliasName() + "'.", e);
		}
	}
	
	private File getRecordFile()
	{
		return new File(_path, getAliasName() + "_" + getPort());
	}
}